Mybatis 您所在的位置:网站首页 mybatis和mybatis plus选哪个 Mybatis

Mybatis

2023-04-12 17:05| 来源: 网络整理| 查看: 265

1.实体类

注意点:别忘了autoResultMap = true

@Data @TableName(value = "report", autoResultMap = true) public class Report implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Integer id; @TableField(typeHandler = ReportUserListTypeHandler.class) private List reportInfo; } 2.公共的ListTypeHandler

提供一个 JSONArray 转换为 Java List集合的处理器 @MappedJdbcTypes指定jdbc的类型 @MappedTypes指定Java的类型

import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.MappedJdbcTypes; import org.apache.ibatis.type.MappedTypes; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @MappedJdbcTypes(JdbcType.ARRAY) @MappedTypes({List.class}) public abstract class ListTypeHandler extends BaseTypeHandler { @Override public void setNonNullParameter(PreparedStatement ps, int i, List parameter, JdbcType jdbcType) throws SQLException { String content = CollUtil.isEmpty(parameter) ? null : JSON.toJSONString(parameter); ps.setString(i, content); } @Override public List getNullableResult(ResultSet rs, String columnName) throws SQLException { return this.getListByJsonArrayString(rs.getString(columnName)); } @Override public List getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return this.getListByJsonArrayString(rs.getString(columnIndex)); } @Override public List getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return this.getListByJsonArrayString(cs.getString(columnIndex)); } private List getListByJsonArrayString(String content) { return StrUtil.isBlank(content) ? new ArrayList() : JSON.parseObject(content, this.specificType()); } /** * 具体类型,由子类提供 * * @return 具体类型 */ protected abstract TypeReference specificType(); } 3.具体的ListTypeHandler

由具体的子类提供List集合泛型类型

import com.alibaba.fastjson.TypeReference; import com.chandol.entity.po.ReportUser; import java.util.List; public class ReportUserListTypeHandler extends ListTypeHandler { @Override protected TypeReference specificType() { return new TypeReference() { }; } } 4.为什么不在公共类直接提供TypeReference

如果在 ListTypeHandler 类中直接提供 TypeReference 这种类型,那就等效于TypeReference



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有